<template>
  <view class="container">
    <u-popup @touchmove.stop.prevent="moveHandle" :show="vendingMachineWenKongShow" :round="20" mode="bottom" @close="closeShow()"  closeOnClickOverlay>
      <view class="warp">
        <view class="u-p-r-20 u-p-l-20 u-p-t-20">
          <view class="u-flex u-row-between u-m-b-30">
            <view class="text">灯光开关</view>
            <u-switch activeColor="#6072FF" v-model="params.lightControl"  size="22"></u-switch>
          </view>
          <view class="input-view" v-if="params.lightControl">
            <view class="input-box" style="" @click="isBatteryNumber(1)">
              <view>启动时间：</view>
              <view class="input-box-sub">
                <view v-if="params.lampStartupTime">
                  {{params.lampStartupTime}}
                </view>
                <view v-else>
                  选择灯控启动时间
                </view>
              </view>
            </view>
            <view class="input-box" style="" @click="isBatteryNumber(2)">
              <view>停止时间：</view>
              <view class="input-box-sub">
                <view v-if="params.lampStopTime">
                  {{params.lampStopTime}}
                </view>
                <view v-else>
                  选择灯控停止时间
                </view>
              </view>
            </view>
          </view>
<!--          <view class="u-flex u-row-between">-->
<!--            <view class="text">风扇</view>-->
<!--            <u-switch activeColor="#6072FF" v-model="params.fanControl" size="22"></u-switch>-->
<!--          </view>-->
          <view class="u-flex u-row-between">
            <view class="text">温度控制</view>
            <view>
              <u-radio-group placement="row" v-model="params.temperatureControl"  @change="radioContentChange($event)">
                <u-radio activeColor="#FF8000" :customStyle="{margin: '30rpx'}" labelSize="28rpx" shape="circle" :name="0" label="关闭"></u-radio>
                <u-radio activeColor="#FF8000" :customStyle="{margin: '30rpx'}" labelSize="28rpx" shape="circle" :name="1" label="制冷"></u-radio>
              </u-radio-group>
            </view>
          </view>
          <view v-if="params.temperatureControl == 1">
            <view class="text">压缩机</view>
            <view class="u-m-l-60 u-m-t-30">
              <view class="wen-du">注意：温差值最高10℃，最低3℃，如启动温度设置为+5℃，即停止温度设置范围是-5℃至+2℃</view>
              <view class="u-flex u-row-between u-m-t-40">
                <view class="text">当前温度（℃）</view>
                <view style="width: 220rpx">
                  <u--input
                      v-model="params.compressorCurrentTemperature"
                      inputAlign="center"
                      disabled
                      :customStyle="{height:30+'rpx'}"
                  ></u--input>
                </view>
              </view>
              <view class="u-flex u-row-between u-m-t-40">
                <view class="text">启动温度（℃）</view>
                <u-number-box v-model="params.compressorStartingTemperature" integer :min="-30" :max="30"></u-number-box>
              </view>
              <view class="u-flex u-row-between u-m-t-40">
                <view class="text">停止温度（℃）</view>
                <u-number-box v-model="params.compressorStopTemperature" integer :min="-30" :max="30"></u-number-box>
              </view>
            </view>
          </view>
        </view>
        <view class="u-flex u-row-around btn">
          <u-button text="取消" :customStyle="cancelCustomStyle" @click="cancel()"></u-button>
          <u-button text="保存" :customStyle="saveCustomStyle" @click="save()"></u-button>
        </view>
      </view>
    </u-popup>
    <u-datetime-picker
        :show="timeShow"
        mode="time"
        :formatter="formatter"
        :closeOnClickOverlay="true"
        :itemHeight = "88"
        ref="datetimePicker"
        @confirm="endDatetimeConfirm($event)"
        @cancel="endDatetimeCancel()"
        @close="endDatetimeCancel()"
    ></u-datetime-picker>
  </view>
</template>

<script>
export default {
  props: {
    dId: {

    }
  },
  data() {
    return {
      vendingMachineWenKongShow: false,
      params:{
        id:'',
        deviceNo:'',
        lightControl:false,
        fanControl:false,
        temperatureControl:0,
        compressorStartingTemperature:0,
        compressorStopTemperature:0,
        compressorCurrentTemperature:'',
        lampStopTime:'',
        lampStartupTime: '',
      },
      timeShow: false,
      timeShowType:-1,
      cancelCustomStyle: {
        width: '232rpx',
        height: '88rpx',
        background: 'rgb(255, 255, 255)',
        borderRadius: '120px',
        color: 'rgba(0, 0, 0, 0.6)',
      },
      device:{},
      saveCustomStyle: {
        width: '232rpx',
        height: '88rpx',
        background: '#6072FF',
        borderRadius: '120px',
        color: '#fff',
      },
    }
  },
  onReady() {
    console.log('是否进入')
    // 微信小程序需要用此写法
    this.$refs.datetimePicker.setFormatter(this.formatter)
  },
  onLoad(){

  },
  methods: {
    init(device) {
      //数据回响
      this.device = device
      this.params.id = device.id
      this.params.deviceNo = device.deviceNo
      this.params.lightControl = device.lightControl
      this.params.fanControl =  device.fanControl
      this.params.temperatureControl = device.temperatureControl
      this.params.compressorStartingTemperature =  device.compressorStartingTemperature
      this.params.compressorStopTemperature =  device.compressorStopTemperature
      this.params.compressorCurrentTemperature = device.compressorCurrentTemperature
      this.params.lampStartupTime = ''
      this.params.lampStopTime = ''
      if(!this.$u.test.isEmpty(device.lampStartupTime)){
        this.params.lampStartupTime = device.lampStartupTime
      }

      if(!this.$u.test.isEmpty(device.lampStopTime)){
        this.params.lampStopTime = device.lampStopTime
      }
      this.vendingMachineWenKongShow = true;
      this.initFuncParamDataValue();
    },
    // 当设备有在线发
    initFuncParamDataValue() {
      if (this.device.networkIntensity > 0) {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        this.sendQueryExternalDeviceParamValue();
        setTimeout(() => {
          this.findOneDeviceById();
        }, 1500)
      }
    },
    // 发送查询串口数据
    sendQueryExternalDeviceParamValue() {
      let params = {
        deviceId: this.device.id,
      }
      this.$api('externalDeviceParamValue.sendQueryExternalVendingDeviceParamValue', params).then(res => {
        if (res.status == 0) {
        }
      })
      .catch(() => {
        uni.hideLoading();
      });
    },
    isBatteryNumber(type){
      this.timeShow = true;
      this.timeShowType = type;

    },
    findOneDeviceById() {

      let param = {
        id: this.device.id,
      }
      this.$api('device.findOneDeviceById', param)
          .then(res => {
            uni.hideLoading();
            if (res.status == 0) {
              this.device = res.data;
              this.params.id = this.device.id;
              this.params.deviceNo = this.device.deviceNo;
              this.params.lightControl = this.device.lightControl;
              this.params.fanControl =  this.device.fanControl;
              this.params.temperatureControl = this.device.temperatureControl;
              this.params.compressorStartingTemperature =  this.device.compressorStartingTemperature;
              this.params.compressorStopTemperature =  this.device.compressorStopTemperature;
              this.params.compressorCurrentTemperature = this.device.compressorCurrentTemperature;
              this.params.lampStartupTime = '';
              this.params.lampStopTime = '';
              if(!this.$u.test.isEmpty(this.device.lampStartupTime)){
                this.params.lampStartupTime = this.device.lampStartupTime;
              }
              if(!this.$u.test.isEmpty(this.device.lampStopTime)){
                this.params.lampStopTime = this.device.lampStopTime;
              }
            } else {
              this.$helpers.toast('请求数据失败:' + res.msg);
            }
          })
          .catch(() => {
            if (type === 'refresh') {
              uni.stopPullDownRefresh();
            }
            uni.hideLoading();
          });
    },
    //时间控件确认
    endDatetimeConfirm(e) {
      // let dateStr = uni.$u.date(e.value, 'hh:MM');
      if(this.timeShowType == 1){
        //开始时间
        this.params.lampStartupTime = e.value + ':00';
      }else if (this.timeShowType == 2){
        this.params.lampStopTime = e.value + ':00';
      }
      this.timeShow = false;
      console.log('时间:', this.params);
    },
    isIntervalValid(startTimeStr, endTimeStr) {
      // 将时间字符串转换为分钟
      const [startHours, startMinutes] = startTimeStr.split(':').map(Number);
      const [endHours, endMinutes] = endTimeStr.split(':').map(Number);

      // 计算总分钟
      const startTotalMinutes = startHours * 60 + startMinutes;
      const endTotalMinutes = endHours * 60 + endMinutes;
      const bool =  ((endTotalMinutes - startTotalMinutes) >= 360 || (endTotalMinutes - startTotalMinutes) <= -1 || (endTotalMinutes - startTotalMinutes) == 0);
      // 检查间隔是否大于等于六小时（360分钟）
      return bool;
    },
    //时间控件取消
    endDatetimeCancel(){
      this.timeShow = false;
    },
    formatter(type, value) {
      if (type === 'hour') {
        return `${value}时`
      }
      if (type === 'minute') {
        return `${value}分`
      }
      return value
    },
    moveHandle() {

    },
    save(){
      console.log(this.params.compressorStopTemperature)
      if(this.params.temperatureControl == 1){
        if ((this.$u.test.isEmpty(this.params.compressorStartingTemperature) && this.params.compressorStartingTemperature != 0)
            || this.params.compressorStartingTemperature < -30
            || this.params.compressorStartingTemperature > 30){
          this.$helpers.toast('启动温度不能为空并且输入范围在-30~30');
          return;
        }
        if ((this.$u.test.isEmpty(this.params.compressorStopTemperature) && this.params.compressorStopTemperature != 0)
            || this.params.compressorStopTemperature < -30
            || this.params.compressorStopTemperature > 30){
          this.$helpers.toast('停止温度不能为空并且输入范围在-30~30');
          return;
        }
          if(this.params.compressorStartingTemperature <= this.params.compressorStopTemperature){
          this.$helpers.toast('启动温度必须大于停止温度');
          return;
        }
        //计算温度差差
        let cha =  this.params.compressorStartingTemperature - this.params.compressorStopTemperature
        console.log("cha",cha)
        if(cha > 10 || cha < 3){
          this.$helpers.toast('差值最高10℃，最低3℃');
          return;
        }
      }
      if(this.params.lightControl){
        console.log('进入了吗')
        if(this.$u.test.isEmpty(this.params.lampStartupTime) || this.$u.test.isEmpty(this.params.lampStopTime)){
          this.$helpers.toast('请设置时间');
          return;
        }
        const isValid = this.isIntervalValid(this.params.lampStartupTime, this.params.lampStopTime); // 校验时间间隔
        console.log(isValid ? '间隔有效' : '间隔无效'); // 输出结果
        if(!isValid){
          this.$helpers.toast('时间间隔必须大于六个小时');
          return;
        }
      }
      uni.showLoading({
        title: '保存中...',
        mask: true
      })

      this.$api('device.updateCustomerBuySet', this.params)
          .then(res => {
            uni.hideLoading();
            if (res.status == 0) {
              this.vendingMachineWenKongShow = false;
              this.$helpers.toast('修改成功');
            } else {
              getApp().err('保存失败', res.msg);
            }
          })
          .catch(() => {
            uni.hideLoading();
          });
    },
    radioContentChange(e){
      this.params.productDisplayType = e
    },
    cancel(){
      this.vendingMachineWenKongShow = false
    },

    //截取后两位:00
    convertTimeFormat(timeStr) {
      // 检查输入格式是否为 HH:mm:ss
      const timeParts = timeStr.split(':');
      if (timeParts.length !== 3) {
        throw new Error('Invalid time format. Expected HH:mm:ss');
      }

      const hours = timeParts[0]; // 获取小时
      const minutes = timeParts[1]; // 获取分钟
      console.log('小时:分钟',`${hours}:${minutes}`);

      // 进行格式转换，返回 mm:hh
      return `${hours}:${minutes}`;
    },
    closeShow() {
      this.vendingMachineWenKongShow = false;
    },

  },
}
</script>

<style lang="scss" scoped>
.container{
  .input-view {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 24rpx;
    margin-bottom: 30rpx;
    .input-box {
      display: flex;
      align-items: center;
      .input-box-sub {
        background-color: #EBECEE;
        padding: 15rpx 20rpx;
        border-radius: 12rpx;
      }
    }
  }
  .warp{
    padding: 30rpx;
    .title{
      color: rgb(0, 0, 0);
      font-size: 32rpx;
      margin-bottom: 40rpx;
    }
    .text{
      color: rgba(0, 0, 0, 0.8);
      font-size: 28rpx;
      letter-spacing:1rpx;
    }
    .wen-du{
      color: #FF0606;
      font-size: 28rpx;
      letter-spacing:1rpx;
    }
    .btn{
      margin-top: 40rpx;
    }

  }

}
</style>
